const mysql = require('mysql2/promise');

// 数据库配置
const dbConfig = {
    host: process.env.DB_HOST || "43.143.253.188",
    port: parseInt(process.env.DB_PORT || "3306", 10),
    user: process.env.DB_USER || "nextjs",
    password: process.env.DB_PASS || "yEAiRE2jcxTyRBy5",
    database: process.env.DB_NAME || "nextjs",
    charset: 'utf8mb4',
    timezone: '+08:00',
    acquireTimeout: 60000,
    timeout: 60000,
};

async function testConnection() {
    let connection;

    try {
        console.log('🚀 测试数据库连接...');
        console.log(`📡 连接地址: ${dbConfig.host}:${dbConfig.port}`);
        console.log(`🗄️ 数据库: ${dbConfig.database}`);
        console.log(`👤 用户: ${dbConfig.user}`);

        // 连接数据库
        connection = await mysql.createConnection(dbConfig);
        console.log('✅ 数据库连接成功！');

        // 测试查询
        console.log('🔍 测试查询...');
        const [results] = await connection.execute('SELECT 1 as test');
        console.log('✅ 查询测试成功:', results[0]);

        // 检查表结构
        console.log('🔍 检查相关表...');
        const [tables] = await connection.execute("SHOW TABLES LIKE 'mount_base'");
        if (tables.length > 0) {
            console.log('✅ mount_base 表存在');

            // 检查表结构
            const [columns] = await connection.execute('DESCRIBE mount_base');
            console.log('📋 mount_base 表结构:');
            columns.forEach(col => {
                console.log(`  ${col.Field}: ${col.Type} ${col.Null === 'NO' ? 'NOT NULL' : 'NULL'} ${col.Key ? `(${col.Key})` : ''}`);
            });

            // 检查现有数据
            const [count] = await connection.execute('SELECT COUNT(*) as count FROM mount_base');
            console.log(`📊 现有坐骑数据: ${count[0].count} 条记录`);

        } else {
            console.log('❌ mount_base 表不存在');
        }

        console.log('✅ 数据库连接测试完成！');

    } catch (error) {
        console.error('❌ 数据库连接测试失败:', error.message);
        throw error;
    } finally {
        if (connection) {
            await connection.end();
            console.log('🔌 数据库连接已关闭');
        }
    }
}

// 执行测试
if (require.main === module) {
    testConnection()
        .then(() => {
            console.log('✅ 测试完成');
            process.exit(0);
        })
        .catch((error) => {
            console.error('❌ 测试失败:', error);
            process.exit(1);
        });
}

module.exports = { testConnection };